#include <signal.h>
#include <sys/signalfd.h>
#include <unistd.h>

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[]) {
    if (argc < 2 || string(argv[1]) == "--help") {
        cout << argv[0] << " sig-num..." << endl;
        return 1;
    }

    cout << argv[0] << ": PID = " << getpid() << endl;

    sigset_t mask;
    sigemptyset(&mask);
    for (int i = 1; i < argc; i++) {
        sigaddset(&mask, stoi(argv[i]));
    }

    if (sigprocmask(SIG_SETMASK, &mask, nullptr) == -1) {
        perror("sigprocmask");
        return 1;
    }

    auto sfd = signalfd(-1, &mask, 0);
    if (sfd == -1) {
        perror("signalfd");
        return 1;
    }

    ssize_t                 n = 0;
    struct signalfd_siginfo fdsiginfo;
    for (;;) {
        n = read(sfd, &fdsiginfo, sizeof(struct signalfd_siginfo));
        if (n != sizeof(struct signalfd_siginfo)) {
            perror("read");
            return 1;
        }

        cout << argv[0] << ": got signal " << fdsiginfo.ssi_signo;
        if (fdsiginfo.ssi_code == SI_QUEUE) {
            cout << "; ssi_pid = " << fdsiginfo.ssi_pid << "; ";
            cout << "ssi_int = " << fdsiginfo.ssi_int;
        }
        cout << endl;
    }
}
